package jiazhong.hfl20250308;

import java.util.ArrayList;

//6.给定⼀个⼤⼩为 n 的集合 nums ,返回其中的多数元素.多数元素是指在集合中出现次数⼤于2/n的元素.
public class ReturnNum {

    public static int majorityElement(ArrayList<Integer> list) {
        int count = 0;// 计数器
        int candidate = 0;// 将元素带出来
        for (int num : list) {// 遍历数组
            if (count == 0) {
                candidate = num;
            }
            count += (num == candidate) ? 1 : -1;
        }
        return candidate;
    }

    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add((int) (Math.random() * 3 + 1));
        }
        System.out.println(list);

        int result = majorityElement(list);
        System.out.println(result);
    }
}
